Skip to content

Fix verification API JSON parsing errors blocking task completion#16

Draft
Copilot wants to merge 3 commits intomainfrom
copilot/fix-verification-button-error
Draft

Fix verification API JSON parsing errors blocking task completion#16
Copilot wants to merge 3 commits intomainfrom
copilot/fix-verification-button-error

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Jan 29, 2026

Verification buttons threw Unexpected token '<', "<!doctype "... errors when API endpoints returned HTML (404/error pages), blocking users from earning points.

Changes

Content-Type validation - Check response headers before parsing:

const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
  console.warn(`API endpoint ${endpoint} returned non-JSON response...`);
  verified = true; // Allow action without verification
}

Error handling hierarchy - Distinguish technical errors from user failures:

  1. Check SyntaxError first (before isUserVerificationFailure flag) - handles edge case where non-ok response has malformed JSON
  2. Re-throw user verification failures (action not completed)
  3. Allow on technical errors (network, parsing, unknown) with console warnings

Test coverage - 14 tests covering HTML responses, malformed JSON, network errors, edge cases

Behavior

Scenario Outcome
API unavailable (404/HTML/network/malformed JSON) Allow action + warning
User hasn't completed action Block with error
API working normally Verify as expected

Maintains backwards compatibility for deployments without verification APIs.

Original prompt

Critical Bug: Verification Buttons Block Task Completion

Error Message:

Verification error: Unexpected token '<', "<!doctype "... is not valid JSON. Please try again later.

Problem

Users cannot complete tasks because the verification system is throwing errors instead of gracefully falling back. The error occurs because:

  1. Line 643 in src/utils/api.ts calls await response.json() without checking if the response is actually JSON
  2. When API endpoints return HTML (404/error pages), JSON parsing fails
  3. Line 674 catches the error but re-throws it, blocking task completion
  4. Users are stuck and cannot earn points

Root Cause Analysis

// Line 636-643: Fetches API response
const response = await fetch(endpoint, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ xHandle: member.x_handle, postUrl: xPost.post_url }),
});

const data = await response.json(); // ❌ FAILS HERE when response is HTML

The code assumes the response is always JSON, but when serverless functions aren't deployed or return 404s, it breaks.

Required Fix

In src/utils/api.ts - Update XPostAPI.verifyAction method (lines 607-702)

Replace the entire fetch/parse logic with proper error handling:

// Call backend API to verify the action on X.com
let verified = false;
try {
  const endpoint = `/api/verify-${actionType}`;
  const response = await fetch(endpoint, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      xHandle: member.x_handle,
      postUrl: xPost.post_url,
    }),
  });

  // Check if response is JSON before parsing
  const contentType = response.headers.get('content-type');
  if (!contentType || !contentType.includes('application/json')) {
    // API endpoint returned HTML (likely 404 or server error)
    console.warn(`API endpoint ${endpoint} returned non-JSON response (Content-Type: ${contentType}). Verification API may not be deployed. Allowing action to proceed.`);
    verified = true; // Allow action without verification
  } else {
    // Response is JSON, safe to parse
    const data = await response.json();
    
    if (!response.ok) {
      // Check if this is an API configuration error (backwards compatibility)
      if (data.error && data.error.includes('Bearer Token not configured')) {
        console.warn('X API not configured, allowing action without verification');
        verified = true;
      } else {
        // This is a real verification failure - user hasn't completed the action
        throw new Error(data.error || `Verification failed. Please complete the ${actionType} action on X.com first, then try again.`);
      }
    } else {
      verified = data.verified;
      
      if (!verified) {
        // User hasn't actually completed the action on X.com
        throw new Error(`Please complete the ${actionType} action on X.com first, then try again. Make sure you're logged into X.com with the account @${member.x_handle}.`);
      }
    }
  }
} catch (error: any) {
  // Handle different error types
  if (error.message.includes('Please complete') || error.message.includes('Please set')) {
    // This is a user-facing error about incomplete actions - re-throw it
    throw error;
  }
  
  // Check for JSON parsing errors (SyntaxError when trying to parse HTML as JSON)
  if (error instanceof SyntaxError || error.message.includes('JSON') || error.message.includes('Unexpected token')) {
    console.warn('Failed to parse API response as JSON. Verification API may not be deployed correctly. Allowing action to proceed:', error);
    verified = true;
  }
  // Network error or API unavailable
  else if (error instanceof TypeError && error.message.includes('fetch')) {
    console.warn('Network error or API unavailable, allowing action without verification:', error);
    verified = true;
  }
  // Unknown error - allow action to proceed (backwards compatible)
  else {
    console.warn('Unexpected error during verification. Allowing action to proceed:', error);
    verified = true;
  }
}

Why This Fix Works

  1. Checks Content-Type BEFORE parsing - Prevents JSON parsing errors
  2. Allows actions when API unavailable - Users can still complete tasks
  3. Still validates when API works - Real verification happens when endpoints are deployed
  4. Backwards compatible - System works with or without API
  5. Clear console warnings - Developers can see what's happening

Expected Behavior After Fix

Scenario Behavior
API endpoints deployed & working ✅ Normal verification, only allow completed actions
API endpoints not deployed (404) ✅ Allow action, warn in console
API returns HTML error page ✅ Allow action, warn in console
Network error ✅ Allow action, warn in console
User hasn't completed action ❌ Block action, show error message

Testing Checklist

After...

This pull request was created from Copilot chat.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI and others added 2 commits January 29, 2026 21:54
…hecking

Co-authored-by: codenimar <119526795+codenimar@users.noreply.github.com>
…ge case test

Co-authored-by: codenimar <119526795+codenimar@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix verification buttons blocking task completion Fix verification API JSON parsing errors blocking task completion Jan 29, 2026
Copilot AI requested a review from codenimar January 29, 2026 22:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants